package jdbc;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Random;

import javax.sql.rowset.serial.SerialBlob;

import org.apache.cassandra.utils.Hex;

import com.google.common.primitives.Bytes;

public class MultiHiveDriverTest extends Thread{
	int i;
	public MultiHiveDriverTest(int i2) {
		i=i2;
	}
	@Override
	public void run(){
		try {
			Random random=new Random();
			String host=System.getProperty("url","jdbc:laud://localhost:9170?data_port=9091&support_function=true&hive=true");
			Connection con;
			Statement statement;
			Class.forName("cn.edu.thu.laud.jdbc.LaUDDriver");
			con = DriverManager.getConnection(host, "", "");
			statement = con.createStatement();
			ResultSet rSet;
			statement.execute("use default with olap");
			try {
				Thread.sleep(1000+random.nextInt(100));
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
			try{
				statement.execute("create table tbtest1(id int,name string) with olap");
			}catch (Exception e) {
				System.err.println(i+":"+e.getMessage());
			}
			//statement.execute("create table tbtest2(id int,age int) with olap");
			statement.execute("show tables with olap");
			//statement.execute("describe  tbtest1 with olap");
			ResultSet rs=statement.getResultSet();
			while(rs.next()){
				System.out.println(i+":"+rs.getObject(1));
			}
			statement.close();

			System.err.println("-------------------close-------------------------");
			con.close();
		} catch (ClassNotFoundException e1) {
			System.err.print(i+":");
			e1.printStackTrace();
		} catch (SQLException e) {
			System.err.print(i+":");
			e.printStackTrace();
		}

	}
	/**
	 * @param args
	 * @throws SQLException 
	 * @throws NullPointerException 
	 */
	public static void main(String[] args) throws Exception {
		for(int i=1;i<10;i++){
			Thread thread=new MultiHiveDriverTest(i);
			thread.start();
		}

	}

	private static  void writeIntoFile(InputStream instream,String filePath) throws IOException, SQLException{
		File file=new File(filePath);

		if(file.isDirectory()){
			throw new SQLException("file not folder..");
		}
		BufferedInputStream in = new BufferedInputStream(instream);        
		FileOutputStream out = new FileOutputStream(file);        

		//  System.out.println("Available bytes:" + in.available());        

		byte[] temp = new byte[4096];        
		int size = 0;        
		try{
			while ((size = in.read(temp)) != -1) {        
				out.write(temp, 0, size);        
			}
		}catch (IOException e) {
			throw e;
		}
		finally{
			try {
				in.close();
			} catch (IOException e) {
				in=null;
			}        
		}
		in.close();
		out.close();
	}
}
